package com.fan.txl.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.BooleanCodec;
import com.base.txl.utils.RxUtils;
import com.elvishew.xlog.XLog;
import com.f2prateek.rx.preferences2.Preference;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringListener;
import com.facebook.rebound.SpringSystem;
import com.fan.txl.R;
import com.fan.txl.data.auth.Auth;
import com.fan.txl.data.base.Rsp;
import com.fan.txl.data.ad.Ad;
import com.fan.txl.data.push.PushMsg;
import com.fan.txl.mock.api.service.AdService;
import com.fan.txl.mock.api.service.AuthService;
import com.fan.txl.mock.api.service.LoadAPIData;
import com.fan.txl.ui.base.RxActivity;
import com.fan.txl.utils.Constants;
import com.fan.txl.utils.Permissions;
import com.hwangjr.rxbus.RxBus;
import com.jakewharton.rxbinding2.view.RxView;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.CrashReport;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.realm.Realm;
import io.realm.internal.IOException;

import static com.fan.txl.utils.Permissions.*;


public class StartUp extends RxActivity implements LoadAPIData {

    public void getAdAPI() {
                getAPIService()
                .getRpcService()
                .rpc(AdService.methodSearch,AdService.service,AdService.requestSearch)
                .compose(RxUtils.<String>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<String>bindUntilEvent(ActivityEvent.STOP))
                //.compose(this.<Rsp<Ad>>bindToLifecycle())
                .subscribe(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String adRsp) {
                        XLog.d("onNext");
                       // XLog.d(adRsp.getData().getAdUrl());
                        //Toast.makeText(StartUp.this, adRsp.getData().getTitle()+"2222222", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof IOException){//ConnectException
                            XLog.d("Throwable");
                        }
                        XLog.e(e);
                    }

                    @Override
                    public void onComplete() {
                        XLog.d("onComplete");
                    }
                });

        //RxTextView.textChanges()
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_up);

        //permisson();

        final Button update=(Button) findViewById(R.id.update);

        SpringSystem springSystem = SpringSystem.create();
        springSystem.createSpring().addListener(new SimpleSpringListener(){
            @Override
            public void onSpringUpdate(Spring spring) {
                super.onSpringUpdate(spring);

            }
        });
        //动画
        //PathInterpolatorCompat.create()
        //RxCheckedTextView.check()
        RxView.clicks(update)
                //.debounce(300, TimeUnit.MILLISECONDS)
                .throttleFirst(300, TimeUnit.MILLISECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {

                    }
                });

        RxBus.get().register(this);
        skip();
        //openComponent(LoginUI.class);
        //finish();
       // createTestData();
    }

    // Create test data
    private void createTestData() {
        Realm realm = Realm.getDefaultInstance();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                for (int i =0;i<2;i++) {
                    PushMsg p = realm.createObject(PushMsg.class,Long.valueOf(i));
                    p.setTitle("title "+i);
                    p.setText(i+" 我们是工厂广告广告广告广告歌等等等等等等");
                    p.setId(Long.valueOf(i));
                    p.setDate(new Date());
                    p.setValidateDate(new Date());
                }
            }
        });
        realm.close();
    }

    private void skip(){
        RxUtils.time(2000, new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                jump();
            }
        });
    }



    private void jump(){
        Preference<String> auth=getRxSharedPreferences().getString(Constants.authName);
        auth.asObservable().map(new Function<String, Auth>() {
            @Override
            public Auth apply(String s) throws Exception {
                Rsp<Auth> rsp = JSON.parseObject(s,  new TypeReference<Rsp<Auth>>() {});
                return rsp.getData();
            }
        }).subscribe(new Consumer<Auth>() {
            @Override
            public void accept(Auth auth) throws Exception {

                openComponent(FeedsUI.class);
                finish();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                openComponent(LoginUI.class);
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }


    @Override
    public void loadData() {
       // getAdAPI();
    }




    protected void permisson(){
        //在使用的时候申请权限
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
               boolean is= ContextCompat.checkSelfPermission(StartUp.this,
                        Manifest.permission.READ_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED;
                e.onNext(is);
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (!aBoolean){
                    if (ActivityCompat.shouldShowRequestPermissionRationale(StartUp.this,
                            Manifest.permission.READ_CONTACTS)) {
                        new AlertDialog.Builder(StartUp.this)
                                .setTitle("通讯录真朋友")
                                .setMessage("对比好友的匹配程度,请授权!")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        ActivityCompat.requestPermissions(StartUp.this,
                                                new String[]{Manifest.permission.READ_CONTACTS},
                                                PERMISSIONS_REQUEST_READ_CONTACTS);
                                    }
                                })
                                .create()
                                .show();
                    }else{
                        ActivityCompat.requestPermissions(StartUp.this,
                                new String[]{Manifest.permission.READ_CONTACTS},
                                PERMISSIONS_REQUEST_READ_CONTACTS);
                    }
                }
            }
        });

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    finish();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            }
        }


}
